package process.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import process.dao.WebSelectorDao;
import process.model.WebSelector;

@Repository("webSelectorDao")
public class WebSelectorDaoImpl extends JdbcDaoSupport implements
		WebSelectorDao {

	@Autowired
	private DataSource dataSource;

	@PostConstruct
	void init() {
		setDataSource(dataSource);
	}

	@Override
	public long insert(WebSelector webSelector) {
		String sql = "INSERT INTO WebSelectors(StoreId, MenuQ, PaginatorQ) "
				+ "VALUES(?,?,?)";
		getJdbcTemplate().update(sql, webSelector.getId(),
				webSelector.getMenuQ(), webSelector.getPaginatorQ());
		return webSelector.getId();
	}

	@Override
	public void update(WebSelector webSelector) {
		String sql = "UPDATE SET WebSelectors MenuQ = ?, PaginatorQ = ? WHERE StoreId = ?";
		getJdbcTemplate().update(sql, webSelector.getMenuQ(),
				webSelector.getPaginatorQ(), webSelector.getId());
	}

	@Override
	public void delete(WebSelector webSelector) {
		String sql = "DELETE FROM WebSelectors WHERE StoreId = ?";
		getJdbcTemplate().update(sql, webSelector.getId());
	}

	@Override
	public WebSelector get(long id) {
		String sql = "SELECT * FROM WebSelectors WHERE StoreId = ?";
		List<Map<String, Object>> results = getJdbcTemplate().queryForList(sql,
				id);
		return results.isEmpty() ? null : rowMapper(results.get(0));
	}

	@Override
	public List<WebSelector> getList() {
		String sql = "SELECT * FROM WebSelectors";
		List<Map<String, Object>> results = getJdbcTemplate().queryForList(sql);
		List<WebSelector> selectors = new ArrayList<WebSelector>();
		for (Map<String, Object> map : results) {
			selectors.add(rowMapper(map));
		}
		return selectors;
	}
	
	private WebSelector rowMapper(Map<String, Object> row) {
		WebSelector selector = new WebSelector();
		selector.setId((Long) row.get("StoreId"));
		selector.setMenuQ((String) row.get("MenuQ"));
		selector.setPaginatorQ((String) row.get("PaginatorQ"));
		return selector;
	}

}
